package com.jingdianjichi.wx.handler;

import com.jingdianjichi.wx.redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class ReceiveMsgHandler implements WxChatMsgHandler {
    private static final String LOGIN_PREFIX = "loginCode";
    @Resource
    private RedisUtil redisUtil;

    @Override
    public WxChatMsgTypeEnum getMsgType() {
        return WxChatMsgTypeEnum.TEST_MSG;
    }

    @Override
    public String dealMsg(Map<String, String> messageType) {
        log.info("触发用户文本事件");
        String fromUserName = messageType.get("FromUserName");
        String toUserName = messageType.get("ToUserName");
        String content = messageType.get("Content");
        if (!"验证码".equals(content)) {
            return "";
        }
        // 验证码生成
        int validCode = ThreadLocalRandom.current().nextInt(1000, 10000);
        String msg = "您当前的验证码是" + validCode + "五分钟有效";
        String numKey = redisUtil.buildKey(LOGIN_PREFIX, String.valueOf(validCode));
        redisUtil.setNx(numKey, fromUserName, 5L, TimeUnit.MINUTES);
        String replaceContent = "<xml>\n" +
                "  <ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>\n" +
                "  <FromUserName><![CDATA[" + toUserName + "]]></FromUserName>\n" +
                "  <CreateTime>12345678</CreateTime>\n" +
                "  <MsgType><![CDATA[text]]></MsgType>\n" +
                "  <Content><![CDATA[" + msg + "]]></Content>\n" +
                "</xml>";
        return replaceContent;
    }
}
